import threading
import socket

from ds.jpegStreamer import JpegStreamer


class HttpServer:
    serverSocket = None
    isThreadRunning = False
    jpegStreamer = None

    class HTTPServerThread(threading.Thread):
        def __init__(self, name="http server"):
            super().__init__(name=name)

        def run(self):
            while True:
                if not HttpServer.isThreadRunning:
                    return
                self.clientConnection, self.clientAddress = HttpServer.serverSocket.accept()
                requestsUri = self.clientAddress[0].split()[-1]
                # if requestsUri == "127.0.0.1":
                HttpServer.jpegStreamer.addClient(self.clientConnection)
                # else:
                #     raise Exception("not found")

    @staticmethod
    def start():
        HttpServer.startServerSocket()

        HttpServer.jpegStreamer = JpegStreamer()
        HttpServer.jpegStreamer.start()

        httpServerThread = HttpServer.HTTPServerThread()
        HttpServer.isThreadRunning = True
        httpServerThread.start()

    @staticmethod
    def startServerSocket():
        HttpServer.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        HttpServer.serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        HttpServer.serverSocket.bind(('0.0.0.0', 8888))
        HttpServer.serverSocket.listen()

    @staticmethod
    def stop():
        HttpServer.isThreadRunning = False



